package com.zjl.spring.第09章_数据校验Validation.E_自定义校验;

import com.zjl.spring.Spring5新特性.日志;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.support.WebExchangeBindException;

import java.util.List;
import java.util.stream.Collectors;
//异常拦截器。将所有异常 都会此数据的拦截
@RestControllerAdvice("com.zjl.spring.第09章_数据校验Validation.E_自定义校验")
public class MyValidatorError {
    private static final Logger log = LoggerFactory.getLogger(MyValidatorError.class);

    /**
     * 自定义验证异常
     * MethodArgumentNotValidException 方法参数无效异常
     */
//    @ResponseStatus(HttpStatus.BAD_REQUEST) //设置状态码为 400
    @ExceptionHandler({MethodArgumentNotValidException.class, WebExchangeBindException.class})
//    @ResponseBody
    public String paramExceptionHandler(BindingResult bindingResult) {
        //那下面这里就是读取具体的校验失败的数据了，可能不是一个，所以其实有一个遍历的过程。
//        BindingResult bindingResult = e.getBindingResult();
        StringBuilder paramErrorMsg = new StringBuilder();
        if (bindingResult.hasErrors()) {

            List<ObjectError> allErrors = bindingResult.getAllErrors();
            for (ObjectError objectError : allErrors) {
                String msg = objectError.getDefaultMessage();
                if (paramErrorMsg.length() == 0) {
                    paramErrorMsg.append(msg);
                } else {
                    paramErrorMsg.append(',');
                    paramErrorMsg.append(msg);
                }
            }
        }
        log.info("--***********{}-----",paramErrorMsg);
        return paramErrorMsg.toString();
    }

    /**
     * 参数校验异常控制处理
     * @param e
     * @return
     */
    @ExceptionHandler(Exception.class)
    public String handleBindException(Exception e, Model model){

        System.out.println(e.getClass());
        return "兜底异常" + e.toString();
    }

}

